

from salt_api.get_info import GetInfo
from cmdb.models import Hosts

class ex_hosts(object):
    def __init__(self):
        self.getinfo = GetInfo()
        self.cmdbinfo = self.getinfo.run()

    def getData(self,args):
        for host in self.cmdbinfo.keys():
            hostcode = host
            # print(self.cmdbinfo)
            ip_wan = self.cmdbinfo[host]['ip_wan']
            ip_lan = self.cmdbinfo[host]['ip_lan']
            configureations = self.cmdbinfo[host]['configureations']
            release = self.cmdbinfo[host]['release']
            os = self.cmdbinfo[host]['os']
            if args == 'init':
                Hosts.objects.create(hostcode=host,
                        ip_wan=ip_wan,ip_lan=ip_lan,
                        configureations=configureations,os=os,release=release)
            else: # host refurbish
                # print('--log: into refurbish ')
                try:
                    print('--log: into refurbish try ')
                    result = Hosts.objects.get(hostcode=hostcode) #检测主机是否存在
                except Exception as e:  # 主机不存在就插入
                    print('---CustomeEroor: ',e) # todo 项目上线时需要把此print写入日志
                    Hosts.objects.create(hostcode=host,
                                         ip_wan=ip_wan, ip_lan=ip_lan,
                                         configureations=configureations, os=os, release=release)



    def run(self,args):
        self.getData(args)


if __name__ == '__main__':
    import django, os, sys
    # from get_info import GetInfo
    ROOT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.insert(0, ROOT_PATH)
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "OpSystem.settings")

    django.setup()
    h = ex_hosts()
    h.run()
